import 'package:dio/dio.dart';
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_chat/config/app_config.dart';
import 'package:flutter_chat/page/chat_list_page.dart';
import 'package:flutter_chat/page/web_page.dart';
import 'package:get_it/get_it.dart';
import 'package:oktoast/oktoast.dart';
import 'package:flutter_chat/page/home_page.dart';
import 'package:shared_preferences/shared_preferences.dart';

/**
 * 登录页面
 */
class LoginPage extends StatefulWidget {
  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  TextEditingController username_controller = TextEditingController(text: "");
  TextEditingController password_controller = TextEditingController(text: "");
  AppConfig appConfig;

  @override
  void initState() {
    appConfig = GetIt.instance<AppConfig>();
  }

  @override
  Widget build(BuildContext context) {
    bool isLogin = false;
    _isLogin() async {
      SharedPreferences prefs = await SharedPreferences.getInstance();
      var login = prefs.getString('login');
      int newTime = new DateTime.now().millisecondsSinceEpoch;
      int loginTime = prefs.getInt('loginTime');
//      int diff = newTime - loginTime;
      int longTime = 60 * 24 * 60 * 30; // 30天内登陆有效
      if (login != null && longTime > (newTime - loginTime) / 1000) {
        isLogin = true;
        Navigator.pushAndRemoveUntil(context,
            new MaterialPageRoute(builder: (context) {
//          return appConfig.isBigScreen ? HomePage() : WebPage();
          return HomePage();
        }), (route) => route == null);
      } else {}
    }

    _isLogin();
//    print(isLogin);
//    login();
//    _isLogin async{
//      Navigator.pushAndRemoveUntil(context,
//          new MaterialPageRoute(builder: (context) {
//            return DartTokenPage({'token', 123131, 'userName'});
//          }), (route) => route == null);
//    }

    return Scaffold(
      body: Container(
        padding: EdgeInsets.symmetric(
          horizontal: MediaQuery.of(context).size.width * 0.1,
        ),
        child: Column(
          mainAxisSize: MainAxisSize.max,
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            TextFormField(
              decoration: InputDecoration(hintText: "用户名"),
              controller: username_controller,
            ),
            TextFormField(
              controller: password_controller,
              decoration: InputDecoration(hintText: "密码"),
            ),
            Row(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                ButtonTheme(
                  minWidth: 250.0,
                  padding: const EdgeInsets.all(5.0),
                  child: RaisedButton(
                    onPressed: () {
                      login();
                    },
//                    color: Colors.white,
//                    textColor: Colors.black87,
                    textColor: Colors.white,
                    // 设置圆角
                    shape: RoundedRectangleBorder(
                      // 设置圆角颜色
                      side: BorderSide(
                        color: Colors.white,
                      ),
                      // 设置圆角角度
                      borderRadius: BorderRadius.all(Radius.circular(5)),
                    ),
                    child: Text("登  录"),
                  ),
                ),
//                RaisedButton(
//                  onPressed: () {
//                    register();
//                  },
//                  child: Text("注册"),
//                ),
              ],
            )
          ],
        ),
      ),
    );
  }

  // 弹出对话框
  Future<bool> showDeleteConfirmDialog1() {
    return showDialog<bool>(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: Text("提示"),
          content: Text("您确定要删除当前文件吗?"),
          actions: <Widget>[
            FlatButton(
              child: Text("取消"),
              onPressed: () => Navigator.of(context).pop(), // 关闭对话框
            ),
            FlatButton(
              child: Text("删除"),
              onPressed: () {
                //关闭对话框并返回true
                Navigator.of(context).pop(true);
              },
            ),
          ],
        );
      },
    );
  }

//  final spinkit = SpinKitFadingCircle(
//    itemBuilder: (BuildContext context, int index) {
//      return DecoratedBox(
//        decoration: BoxDecoration(
//          color: index.isEven ? Colors.red : Colors.green,
//        ),
//      );
//    },
//  );
  void login() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setString('login', 'login');
    print(133);
    Navigator.pushAndRemoveUntil(context,
        new MaterialPageRoute(builder: (context) {
      return HomePage();
    }), (route) => route == null);
  }
// 备份
  /*void login() async {
    Dio dio = Dio(BaseOptions(baseUrl: GetIt.instance<AppConfig>().apiHost));
    print(username_controller.text.toString());
    try {
      print(username_controller.text.toString());
      var name = username_controller.text.toString();
      var pass = password_controller.text.toString();
      Response<Map<String, dynamic>> response =
          await dio.post<Map<String, dynamic>>(
        "/login",
        data: {
          "cimId": name,
          "password": pass,
        },
//        options: Options(
//            followRedirects: false,
//            validateStatus: (status) {
//              return status < 500;
//            }),
      );
      print(response.data['data']);
      if (response.data['status'] == 200) {
        SharedPreferences prefs = await SharedPreferences.getInstance();
        prefs.setString('login', 'login');
        prefs.setString('uid', response.data['data']['uid']);
        prefs.setString('cimId', response.data['data']['cimId']);
        prefs.setString('nickname', response.data['data']['nickname']);
        prefs.setString('faceImage', response.data['data']['faceImage']);
        prefs.setString('faceImageBig', response.data['data']['faceImageBig']);
        prefs.setString('qrcode', response.data['data']['qrcode']);
        prefs.setString('cid', response.data['data']['cid']);
        prefs.setString('createTime', response.data['data']['createTime']);
        int loginTime = new DateTime.now().millisecondsSinceEpoch;
        prefs.setInt('loginTime', loginTime);
        print('登陆成功');
        print(loginTime);
        *//*Navigator.push(context, new MaterialPageRoute(builder: (context) {
          return HomePage();
//          return appConfig.isBigScreen ? HomePage() : WebPage();
        }));*//*
        Navigator.pushAndRemoveUntil(context,
            new MaterialPageRoute(builder: (context) {
          return HomePage();
//          return appConfig.isBigScreen ? HomePage() : WebPage();
        }), (route) => route == null);
//        Navigator.of(context).push(MaterialPageRoute(builder: (context) {
//          return DartTokenPage(response.data['data']);
//        }));
//        SpinKitFadingCircle(
//          itemBuilder: (BuildContext context, int index) {
//            return DecoratedBox(
//              decoration: BoxDecoration(
//                color: index.isEven ? Colors.red : Colors.green,
//              ),
//            );
//          },
//        );
//        await spinkit();
        //弹出对话框并等待其关闭
//        bool delete = await showDeleteConfirmDialog1();
//        if (delete == null) {
//          print("取消删除");
//        } else {
//          print("已确认删除");
//          //... 删除文件
//        }
      } else {
        print(response.data['msg']);
      }
//      if (response is String) {
//        print('是string类型');
//      } else if (response is int) {
//        print('int');
//      } else {
//        print('其他类型');
//      }
      *//*Navigator.of(context).push(MaterialPageRoute(builder: (context) {
        return DartTokenPage(
          token: name,
          fromUserId: 81034941,
          userName: pass,
        );
      }));*//*
      print('response');
    } catch (error) {
      print('error');
      print(error);
      print('error');
    }

//    print("登录结果:$response");
//    if (response != null &&
//        response.data != null &&
//        response.data['code'] == 1 &&
//        response.data['data']['access_token'] != null) {
//      //登录成功
//      String token = response.data['data']['access_token'];
//      int fromUserId = response.data['data']['userId'];
//      String userName = response.data['data']['userName'];
//
//      Navigator.of(context).push(MaterialPageRoute(builder: (context) {
//        return ChatListPage(
//          token: token,
//          fromUserId: fromUserId,
//          userName: userName,
//        );
//      }));
//    }
  }*/

  void register() async {
    Dio dio = Dio(BaseOptions(baseUrl: GetIt.instance<AppConfig>().apiHost));

    Response<Map<String, dynamic>> response =
        await dio.post<Map<String, dynamic>>(
      "/register",
      data: {
        'username': username_controller.text.toString(),
        'password': password_controller.text.toString(),
      },
    );

    print("注册结果:$response");
    if (response != null &&
        response.data != null &&
        response.data['code'] == 1) {
      showToast(response.data['msg']);
    } else {
      showToast("注册失败");
    }
  }
//  _requestLogisticDetal(BuildContext context) async {
//    var path = "http://v.senderPhone=&receiverPhone=&dtype=&key=be0d84e149f047b1fc32b50b50d9fc7f";
//    var params = {"com": Provider.of<LogisticsDetalProvide>(context).logisticsId, "no": "YT9073133846767"};
//    Response response = await Dio().post(path, queryParameters: params);
//    LogisticsDetalEntity logisticsDetalEntity = LogisticsDetalEntity.fromJson(json.decode(response.toString()));
//    if (logisticsDetalEntity.resultcode == "200") {
//      setdata(logisticsDetalEntity);//存储
//      Provider.of<LogisticsDetalProvide>(context).setLogisticsDetalEntity(logisticsDetalEntity);
//    } else {
//      ToastOk.show(msg: logisticsDetalEntity.reason);
//    }
//  }
}
